package com.ezlcp.form.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.base.entity.JsonPageResult;
import com.ezlcp.commons.base.entity.JsonResult;
import com.ezlcp.commons.base.entity.QueryData;
import com.ezlcp.commons.base.search.QueryFilter;
import com.ezlcp.commons.constant.StatusEnum;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.ContextUtil;
import com.ezlcp.form.entity.Form;
import com.ezlcp.form.service.EntityColServiceImpl;
import com.ezlcp.form.service.EntityServiceImpl;
import com.ezlcp.form.service.FormServiceImpl;
import com.ezlcp.form.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ezlcp/form/form")
@Tag(name = "表单（主表）定义")
public class FormController extends BaseController<Form> {
    @Resource
    FormServiceImpl formService;

    @Resource
    EntityServiceImpl entityService;

    @Resource
    EntityColServiceImpl entityColService;

    @Override
    protected void handleFilter(QueryFilter filter) {
        String tenantId = ContextUtil.getCurrentTenantId();
        if (StringUtils.isNotEmpty(tenantId)) {
            filter.addQueryParam("Q_f.tenant_id_S_EQ", tenantId);
        }
    }

    @Operation(summary = "从实体创建表单")
    @PostMapping("/createFromEntity")
    public JsonResult createFromEntity(@RequestBody Form form) {
        if (form == null || StringUtils.isEmpty(form.getEntId()) || StringUtils.isEmpty(form.getModuleId())
                || form.getFmType() == null || form.getFmCols() == null) {
            return JsonResult.Fail("common.paramError");
        }
        return formService.createFromEntity(form.getEntId(), form.getModuleId(), form.getFmType(), form.getFmCols());
    }

    @Operation(summary = "修改表单")
    @PostMapping("/saveForm")
    public JsonResult saveForm(@RequestBody JSONObject object) {
        var form = object.getObject("form", Form.class);
        String delIds = object.getString("deleteIds");
        if (form == null || form.getControls() == null || form.getControls().isEmpty() || StringUtils.isEmpty(form.getFmId())
                || StringUtils.isEmpty(form.getFmName())) {
            return JsonResult.Fail("common.paramError");
        }
        var oldForm = formService.get(form.getFmId());
        if (oldForm != null) {
            if (oldForm.getSeq() != form.getSeq() || oldForm.getStatus() == StatusEnum.deleted.getValue()) {
                return JsonResult.Fail("common.dataChange");
            }
        }
        JSONObject logData = new JSONObject();
        logData.put("new", form);
        logData.put("old", oldForm);
        logService.saveSystemLog(getComment(), "save", form.getFmId(), JSON.toJSONString(logData));
        return formService.saveForm(form, delIds);
    }

    @Operation(summary = "设计器中修改表单页面")
    @PostMapping("/editFormJson")
    public JsonResult editFormJson(@RequestBody JSONObject formJson) {
        String formId = formJson.getString(FormServiceImpl.FORM_ID_KEY);
        if (StringUtils.isEmpty(formId)) {
            return JsonResult.Fail("common.paramError");
        }
        var form = formService.getById(formId);
        if (form == null) {
            return JsonResult.Fail("common.paramError");
        }
        var object = formJson.getJSONObject(FormServiceImpl.FORM_JSON_KEY);
        formService.saveFormJson(form, object);
        return JsonResult.Success("common.handleSuccess");
    }

    @Operation(summary = "删除某个表单")
    @PostMapping("/delete")
    public JsonResult delete(@Parameter(description = "主键Id") @RequestParam("pkId") String pkId) {
        if (StringUtils.isEmpty(pkId)) {
            return JsonResult.Fail("common.paramError");
        }
        var form = formService.getById(pkId);
        if (form == null) {
            return JsonResult.Fail("common.paramError");
        }
        return formService.deleteForm(form);
    }

    @Operation(summary = "根据实体列重新生成表单控件（一般用于实体字段修改之后）")
    @PostMapping("/getControlsFromEntity")
    public JsonResult getControlsFromEntity(@Parameter(description = "表单ID") @RequestParam("formId") String formId,
                                            @Parameter(description = "关联实体ID") @RequestParam("entityId") String entityId) {
        if (StringUtils.isEmpty(formId) || StringUtils.isEmpty(entityId)) {
            return JsonResult.Fail("common.paramError");
        }
        return formService.getControlsFromEntity(formId, entityId);
    }

    @Operation(summary = "发布表单或重新发布表单")
    @PostMapping("/publish")
    public JsonResult publish(@Parameter(description = "表单ID") @RequestParam("formId") String formId) {
        if (StringUtils.isEmpty(formId)) {
            return JsonResult.Fail("common.paramError");
        }
        return formService.publish(formId);
    }

    @Operation(summary = "获取自定义表单实例数据")
    @PostMapping("/getFormData")
    public JsonResult getFormData(@Parameter(description = "表单ID") @RequestParam("formId") String formId,
                                  @Parameter(description = "预览") @RequestParam(value = "isPreview") boolean isPreview,
                                  @Parameter(description = "表单记录ID") @RequestParam(value = "recordId", required = false) String recordId) {
        if (StringUtils.isEmpty(formId)) {
            return JsonResult.Fail("common.paramError");
        }
        return formService.getFormData(formId, recordId, isPreview);
    }

    @Operation(summary = "获取一条引用实体记录")
    @PostMapping("/getRefEntityShowText")
    public JsonResult getRefEntityShowText(@Parameter(description = "实体ID") @RequestParam("entId") String entId,
                                           @Parameter(description = "表单记录ID") @RequestParam(value = "recordId") String recordId) {
        if (StringUtils.isEmpty(entId) || StringUtils.isEmpty(recordId)) {
            return JsonResult.Fail("common.paramError");
        }
        return entityService.getRefEntityShowText(entId, recordId);
    }

    @Operation(summary = "分页查询引用实体记录(关联记录选择)")
    @PostMapping("/selectRefEntity")
    public JsonPageResult selectRefEntity(@RequestBody JSONObject data) {
        QueryData params = new QueryData();
        String colId = data.getString("colId"); //实体列ID
        if (StringUtils.isEmpty(colId)) {
            return JsonPageResult.getFail("common.paramError");
        }
        var entityCol = entityColService.get(colId);
        if (entityCol == null || StringUtils.isEmpty(entityCol.getRefEntId())) {
            return JsonPageResult.getFail("common.paramError");
        }
        String lang = data.getString("lang"); //当前语言
        boolean noDeleted = data.getBooleanValue("noDeleted", false);
        params.setKey(data.getString("key"));
        params.setPageNo(data.getInteger("pageNo"));
        params.setPageSize(data.getInteger("pageSize"));
        params.setSortField(data.getString("sortField"));
        params.setSortOrder(data.getString("sortOrder"));
        return entityService.selectRefEntRecord(params, entityCol.getRefEntId(), lang, noDeleted);
    }

    @Operation(summary = "保存自定义表单记录")
    @PostMapping("/saveFormData")
    public JsonResult saveFormData(@RequestBody JSONObject object) {
        if (object == null) {
            return JsonResult.Fail("common.paramError");
        }
        String formIdKey = "_f_o_r_m_i_d_";
        String formId = object.getString(formIdKey);
        if (StringUtils.isEmpty(formId)) {
            return JsonResult.Fail("common.paramError");
        }
        object.remove(formIdKey);
        return formService.saveFormData(formId, object);
    }

    @Operation(summary = "删除自定义表单记录")
    @PostMapping("/delFormData")
    public JsonResult delFormData(@Parameter(description = "表单记录ID") @RequestParam("recordId") String recordId,
                                  @Parameter(description = "表单ID") @RequestParam("formId") String formId) {
        if (StringUtils.isEmpty(formId) || StringUtils.isEmpty(recordId)) {
            return JsonResult.Fail("common.paramError");
        }
        return formService.delFormData(formId, recordId);
    }


    @Operation(summary = "批量删除自定义表单记录")
    @PostMapping("/batchDelFormData")
    public JsonResult batchDelFormData(@Parameter(description = "ID数组，逗号分隔") @RequestParam("ids") String ids,
                                       @Parameter(description = "表单ID") @RequestParam("formId") String formId) {
        if (StringUtils.isEmpty(formId) || ids == null ) {
            return JsonResult.Fail("common.paramError");
        }
        return formService.batchDelFormData(formId, ids.split(","));
    }

    @Operation(summary = "查询某实体对应的所有发布的表单")
    @PostMapping("/getListByEntId")
    public JsonResult getListByEntId(@Parameter(description = "实体ID") @RequestParam("entId") String entId) {
        if (StringUtils.isEmpty(entId)) {
            return JsonResult.Fail("common.paramError");
        }
        var data = formService.getListByEntId(entId);
        JsonResult result = JsonResult.Success("common.handleSuccess");
        result.setData(data);
        return result;
    }

    @Override
    public JsonResult save(Form entity, BindingResult validResult) throws Exception {
        return JsonPageResult.getFail("common.apiClose");
    }

    @Override
    public JsonPageResult getAll() {
        return JsonPageResult.getFail("common.apiClose");
    }

    @Override
    public JsonResult del(@RequestParam(value = "id") String id) {
        return JsonResult.Fail("common.apiClose");
    }

    @Override
    public BaseService getBaseService() {
        return formService;
    }

    @Override
    public String getComment() {
        return "表单（主表）定义";
    }
}